/* Copyright (c) 2013 fab-o-lab

 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
*/
package com.fabolab.jetset.core.wiki;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import com.fabolab.jetset.core.config.model.Context;
import com.fabolab.jetset.core.servlet.http.HttpServletRequest;


public class WikiUtils {
	private boolean isPublish = false;
	private String fileExtension = "html";
	
	public boolean isPublish() {
		return isPublish;
	}

	public void setPublish(boolean isPublish) {
		this.isPublish = isPublish;
		if (isPublish){
			setFileExtension("html");
		}else
		{
			setFileExtension("wki");
		}
	}

	public String getFileExtension() {
		return fileExtension;
	}

	public void setFileExtension(String fileExtension) {
		this.fileExtension = fileExtension;
	}
	
	public String extractPageTitle(String fileName){
		String result = fileName;
		try{
			result = fileName.substring(0,fileName.indexOf('.'));
		}
		catch(Exception e){
			
		}
		return(result);
	}

	public String parseMenu(String menuText) {
		// with |
		menuText = menuText.replaceAll("\\[\\[([^\\]\\]]*?)\\|(.*?)\\]\\]",
				"<li><a href=\"$2\">$1</a></li>"); 
		// without |
		menuText = menuText.replaceAll("\\[\\[([^\\|]*?)\\]\\]",
				"<li><a href=\"$1\">$1</a></li>");
		menuText = menuText.replaceAll("\n", "");
		if(isPublish){
			menuText = menuText.replaceAll("\\.wki","\\.html");
		}
		return menuText;
	}

	public String parseWiki(String text) {
		try{
		// table start

		text = text.replaceAll("(^|\\n)\\{\\|([^\\n]*)",
				"$1<table class=\"text_area\" $2><tr>");
		//        
		// // table end
		text = text.replaceAll("(^|\\n)\\|\\}", "$1<\\/tr><\\/table>");
		//        
		// // table caption
		text = text.replaceAll("(^|\\n)\\|\\+([^\\n]*)",
				"<caption>$2<\\/caption>");
		//        
		// // table new row
		text = text.replaceAll("(^|\\n)\\|\\-", "<\\/tr><tr>");
		//        
		// // table data
		text = text.replaceAll("(^|\\n)\\|\\s([^\\n]*)",
				"(^|\\n)\\|\\s([^\\n]*)");

		// text = text.replace(/(^|\n)\|\s([^\n]*)/g, function(str, $1, $2)
		// {
		// $2 = $2.replace(/(\|\|)/g, "<\/td><td>");
		// return "<td>" + $2 + "<\/td>";
		// });
		//
		//image
		text = text.replaceAll("\\[\\[\\[!([^\\]\\]]*?)\\|(.*?)\\]\\]\\]",
				"<span><img src=\"files/$2\"><br>$1<\\span>");
		// image without |
		text = text.replaceAll("\\[\\[\\[!([^\\|]*?)\\]\\]\\]",
				"<img src=\"files/$1\">");
		// document link 
		text = text.replaceAll("\\[\\[\\[([^\\]\\]]*?)\\|(.*?)\\]\\]\\]",
				"<a class=\"document\" href=\"files/$2\" target=\"_new\">$1<\\/a>");		
		// document without |
		text = text.replaceAll("\\[\\[\\[([^\\|]*?)\\]\\]\\]",
				"<a class=\"document\" href=\"files/$1\" target=\"_new\">$1<\\/a>");		
		// // Backup link
		// with |
		text = text.replaceAll("\\[\\[backup,([^\\]\\]]*?)\\|(.*?)\\]\\]",
				"<a class=\"backup\" href=\"?cmd=backup&source=$1&file=$2\">$2<\\/a>");		
		// // links
		// with |
		text = text.replaceAll("\\[\\[([^\\]\\]]*?)\\|(.*?)\\]\\]",
				"<a class=\"world\" href=\"$2\">$1<\\/a>"); // "<a
																				// class=\"wiki\"
																				// onclick='go_to(\"$2\")'>$1<\/a>");
		// without |
		text = text.replaceAll("\\[\\[([^\\|]*?)\\]\\]",
				"<a class=\"world\" href=\"$1\">$1<\\/a>");
		// {
		// if($1.match("://"))
		// return "<a class=\"world\" href=\"" + $1 + "\" target=\"_blank\">" +
		// $1 + "<\/a>";
		// if(page_exists($1))
		// return "<a class=\"link\" onclick='go_to(\"" + valid_name($1)
		// +"\")'>" + $1 + "<\/a>";
		// else
		// return "<a class=\"unlink\" onclick='go_to(\"" + valid_name($1)
		// +"\")'>" + $1 + "<\/a>";
		// }); //"<a class=\"wiki\" onclick='go_to(\"$1\")'>$1<\/a>");
		// lists
		text = text.replaceAll("(^|\\n)\\+\\s([^\\n\\+]*)",
				"$1<ul><li>$2<\\/li><\\/ul>");
		text = text.replaceAll("(^|\\n)\\+\\+\\s([^\\n\\+]*)",
				"$1<ul><ul><li>$2<\\/li><\\/ul><\\/ul>");
		text = text.replaceAll("(^|\\n)\\+\\+\\+\\s([^\\n\\+]*)",
				"$1<ul><ul><ul><li>$2<\\/li><\\/ul><\\/ul><\\/ul>");
		text = text.replaceAll("(^|\\n)\\+\\+\\+\\+\\s([^\\n\\+]*)",
				"$1<ul><ul><ul><ul><li>$2<\\/li><\\/ul><\\/ul><\\/ul><\\/ul>");
		for (int i = 0; i < 4; i++) {
			text = text.replaceAll("\\<\\/ul\\>\\<ul\\>", "");
			text = text.replaceAll("\\<\\/ul\\>\\n\\<ul\\>", "");
		}
		// numbererd lists
		text = text.replaceAll("(^|\\n)#\\s([^\\n\\+]*)",
				"$1<ol><li>$2<\\/li><\\/ol>");
		text = text.replaceAll("(^|\\n)##\\s([^\\n\\+]*)",
				"$1<ol><ol><li>$2<\\/li><\\/ol><\\/ol>");
		text = text.replaceAll("(^|\\n)###\\s([^\\n\\+]*)",
				"$1<ol><ol><ol><li>$2<\\/li><\\/ol><\\/ol><\\/ol>");
		text = text.replaceAll("(^|\\n)####\\s([^\\n\\+]*)",
				"$1<ol><ol><ol><ol><li>$2<\\/li><\\/ol><\\/ol><\\/ol><\\/ol>");
		for (int i = 0; i < 4; i++) {
			text = text.replaceAll("\\<\\/ol\\>\\<ol\\>", "");
			text = text.replaceAll("\\<\\/ol\\>\\n\\<ol\\>", "");
		}
		// headers
		text = text.replaceAll("(^|\\n)!([^!].*)", "<h2>$2<\\/h2>");
		text = text.replaceAll("(^|\\n)!!([^!].*)", "<h3>$2<\\/h3>");
		text = text.replaceAll("(^|\\n)!!!(.*)", "<h4>$2<\\/h4>");
		// <b>
		text = text.replaceAll("(^|\\n|\\s|\\>|\\/)\\*(.*?)\\*",
				"$1<b>$2<\\/b>");
		// <i>
		text = text.replaceAll("(^|\\n|\\s|\\>|\\*)\\/(.*?)\\/",
				"$1<i>$2<\\/i>");
		// <u>
		text = text.replaceAll("(^|\\n|\\s|\\>|\\*)_(.*?)_", "$1<u>$2<\\/u>");
		// <hr>
		text = text.replaceAll("(^|\\n)\\-\\-\\-(\\n|$)", "<hr>");
		// <strike>
		// text = text.replace(/(^|\n|\s|\>|\*)\-(.*?)\-/g,
		// "$1<strike>$2<\/strike>");

		text = text.replaceAll("(\\<\\/h.\\>)\\n", "$1");
		text = text.replaceAll("(\\<\\/ul\\>)\\n", "$1");
		text = text.replaceAll("(\\<\\/ol\\>)\\n", "$1");
		text = text.replaceAll("(\\<\\/li\\>)\\n", "$1");

		// if(ie == true)
		// {
		// text = escape(text);
		// text = text.replace("%OD%OA", "<br>");
		// text = unescape(text);
		// }
		

		// Active form processing
		text = text.replaceAll("�form\\|(.*?)\\|(.*?)\\|(.*?)�",
		"<script language='javascript'>var dataform_$1_id=$3;</script><span id='dataform_$1_button' onClick=\"makeAsyncRequest('data.wki?cmd=viewform&table=$1&fields=$2&id=' + dataform_$1_id, 'dataform_$1')\"></span>"
				+ "<span id='dataform_$1'></span><script language='javascript'>document.getElementById('dataform_$1_button').onclick();</script>");
		
		// Form processing
		// TODO use a hash table to lookup actions
		text = text.replaceAll("�form\\|(.*?)\\|(.*?)�",
		"<form class='wkiform' method=\"post\" name=\"wkifrm\"><fieldset class='wkiform'><legend class='wkiform'>$1</legend><input type=\"hidden\" name=\"cmd\" value=\"saveform\"><input type=\"hidden\" name=\"wkifrm_$1\" value=\"$1\">");
		// Text field
		text = text.replaceAll("�text\\|(.*?)\\|(.*?)�",
		"<label class=\"wkiform\" for=\"wkifldstr_$1\">$1</label><input class='wkiform' type=\"text\" name=\"wkifldstr_$1\" id=\"wkifldstr_$1\" size=\"$2\"><br class='wkiform' />");
		// Number field
		text = text.replaceAll("�number\\|(.*?)\\|(.*?)�",
		"<label class=\"wkiform\" for=\"wkifldstr_$1\">$1</label><input class='wkiform' type=\"text\" name=\"wkifldnbr_$1\" id=\"wkifldnbr_$1\" size=\"$2\"><br class='wkiform' />");
		// Text field lookup
		text = text.replaceAll("�textlookup\\|(.*?)\\|(.*?)\\|(.*?)\\|(.*?)�",
		"<script language='javascript'>var textlookup_$1_id=$1;</script><span id='textlookup_$1_button' onClick=\"makeAsyncRequest('data.wki?cmd=lookup&table=$3&fields=$4','wkifldstr_$1')\"></span>"
		+ "<label class=\"wkiform\" for=\"wkifldstr_$1\">$1</label><select class='wkiform' name=\"wkifldstr_$1\" id=\"wkifldstr_$1\" ></select><br class='wkiform' />" 
		+ "<script language='javascript'>document.getElementById('textlookup_$1_button').onclick();</script>");
		// Number field lookup
		text = text.replaceAll("�numberlookup\\|(.*?)\\|(.*?)\\|(.*?)\\|(.*?)�",
		"<label class=\"wkiform\" for=\"wkifldstr_$1\">$1</label><input class='wkiform' type=\"text\" name=\"wkifldnbr_$1\" id=\"wkifldnbr_$1\" size=\"$2\"><br class='wkiform' />");
		// Date field
		text = text.replaceAll("�date\\|(.*?)\\|(.*?)�",
		"<label class=\"wkiform\" for=\"wkifldstr_$1\">$1</label><input class='wkiform' type=\"text\" name=\"wkiflddat_$1\" id=\"wkiflddat_$1\" size=\"$2\"><br class='wkiform' />");

		text = text.replaceAll("�end-form�",
		"<input class='wkiform' type=\"submit\" value=\"OK\"></fieldset></form>");
		
		

		// List processing
		text = text.replaceAll("�list\\|(.*?)\\|(.*?)\\|(.*?)�",
		"<span id='datagrid_$1_button' onClick=\"makeHttpRequest('data.wki?cmd=load&table=$1&fields=$2&selectable=$3&where=' + document.getElementById('datagrid_$1_where').value, 'datagrid_$1')\">loading...</span>"
				+ "<span id='datagrid_$1'>...</span><input type='hidden' id='datagrid_$1_where' value=\"\" /><script language='javascript'>document.getElementById('datagrid_$1_button').onclick();</script>");
		// Horizontal menu for list
		// �listmenu|table|title,action,title,action,..�
		text = text.replaceAll("�listmenu\\|(.*?)\\|(.*?)\\|(.*?)�",
				"<span id='listmenu_$1_button' onClick=\"makeAsyncRequest('data.wki?cmd=listmenu&table=$1&actions=$2&fields=$3', 'listmenu_$1')\">loading...</span>"
						+ "<span id='listmenu_$1'>...</span><script language='javascript'>document.getElementById('listmenu_$1_button').onclick();</script>");
		
		// Horizontal menu
		// Syntax �tabmenu�
		//        �tab|page title|page url|selected�
		//        �end-tabmenu�
		text = text.replaceAll("�tabmenu�(.*?)\\n","<div class=\"ddoverlap\"><ul>");
		text = text.replaceAll("�tab\\|(.*?)\\|(.*?)\\|(.*?)�(.*?)\\n",
		"<li class=\"$3\"><a href=\"$2\">$1</a></li>");
		text = text.replaceAll("�end-tabmenu�(.*?)\\n","</ul><br style=\"clear: left\" /></div>");

		// Gallery
		// �gallery|pagetitle|image,title,image,title,..�
		text = text.replaceAll("�gallery\\|(.*?)\\|(.*?)�",
				"<span id='gallery_$1_button' onClick=\"makeAsyncRequest('$1.wki?cmd=viewgallery&page=$1&images=$2', 'gallery_$1')\">loading...</span>"
						+ "<span id='gallery_$1'>...</span><script language='javascript'>document.getElementById('gallery_$1_button').onclick();</script>");

		// Data template
		// �template|name|table|field1,field99|where clause�
		text = text.replaceAll("�template\\|(.*?)\\|(.*?)\\|(.*?)\\|(.*?)�",
				"<span id='template_$1_button' onClick=\"makeAsyncRequest('data.wki?cmd=viewtemplate&template=$1&table=$2&fields=$3&where=$4', 'template_$1')\">loading...</span>"
						+ "<span id='template_$1'>...</span><script language='javascript'>document.getElementById('template_$1_button').onclick();</script>");

		// Data filter
		// �filter|table|field1,type1,field99,type99�
		text = text.replaceAll("�filter\\|(.*?)\\|(.*?)�",
				"<span id='filter_$1_button' onClick=\"makeAsyncRequest('data.wki?cmd=datafilter&table=$1&fields=$2', 'filter_$1')\">loading...</span>"
						+ "<span id='filter_$1'>...</span><script language='javascript'>document.getElementById('filter_$1_button').onclick();</script>");

		// Search box
		// �search|name|keywords�
		text = text.replaceAll("�search\\|(.*?)\\|(.*?)�",
				"<div><input type='text' id='search_$1_keywords' value='$2' class='search'/>"
				+ "<img src='img/btn_go_26x21.gif' id='search_$1_button' class='search' onClick=\"makeAsyncRequest('data.wki?cmd=search&keywords=' + document.getElementById('search_$1_keywords').value, 'search_$1')\" />"
				+ "</div><br /><span style='clear:left;' id='search_$1'></span>");
				//+ "<script language='javascript'>document.getElementById('search_$1_button').onclick();</script>");
	
		
		// Newline
		// <br>
		//text = text.replaceAll("\\n\\n", "</p><p>");
		// text = "<p>" + text + "</p>";		
		text = text.replaceAll("\\n", "<br>");
		}catch(Exception e){
			text = e.getMessage();
		}
		
		
		if(isPublish){
			text = text.replaceAll("\\.wki","\\.html");
		}
		

		return text;
	}

	public String getLink(String $1, String $2) {
		if ($2.matches("://"))
			return "<a class=\"world\" href=\"" + $2 + "\" target=\"_blank\">"
					+ $1 + "<\\a>";
		if (pageExists($2))
			return "<a class=\"link\" onclick='go_to(\"" + validName($2)
					+ "\")'>" + $1 + "<\\a>";
		else
			return "<a class=\"unlink\" onclick='go_to(\"" + validName($2)
					+ "\")'>" + $1 + "<\\a>";
	}

	public boolean pageExists(String file) {
		return (true);
	}

	public String validName(String file) {
		return (file);
	}

	public String getFile(String fileName) {
		// TODO load file
		String text = "";
		File file = new File(fileName);
		System.out.println("getting " + file.getPath());
		BufferedReader reader;
		try {
			reader = new BufferedReader(new FileReader(file));

			String line;

			while ((line = reader.readLine()) != null) {
				text += line + "\n";
			}

			reader.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			text = "Error finding template.";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			text = "Error reading template";
		} catch (Exception e){
			text = "Error reading template";
		}

		return (text);
	}
	
	
	public String composePage(Context context, String template,String wiki, String menu) {
		// TODO replace template body and menu in template
		String result = "";
		try{
		result = template.replaceFirst("�fhs.body�", wiki);
		result = result.replaceFirst("�fhs.menu�", menu);
		result = result.replaceFirst("�fhs.header1�", context.getResources()
				.getString("fhs.header1"));
		result = result.replaceFirst("�fhs.header2�", context.getPageTitle());
		result = result.replaceFirst("�fhs.title�", context.getPageTitle());		
		result = result.replaceFirst("�fhs.edit�", context.getResources()
				.getString("fhs.edit"));		
		result = result.replaceFirst("�fhs.imageupload�", context.getResources()
						.getString("fhs.imageupload"));
		result = result.replaceFirst("�fhs.editmenu�", context.getResources()
				.getString("fhs.editmenu"));
		result = result.replaceFirst("�fhs.edit.url�", context.getPath()
				+ "?cmd=edit");
		result = result.replaceFirst("�fhs.editmenu.url�", context.getPath()
				+ "?cmd=editmenu");
		result = result.replaceFirst("�fhs.imageupload.url�", context.getPath()
				+ "?cmd=askimage");		
		result = result.replaceFirst("�fhs.prefs�", context.getResources()
				.getString("fhs.prefs"));
		result = result.replaceFirst("�fhs.copyright�", context.getResources()
				.getString("fhs.copyright"));
		}
		catch(Exception e){
			e.printStackTrace();
		}

		return (result);
	}
	
	
}
